package com.goldsprite.gameframeworks.ruletilemap.core;

import java.util.*;

public class RuleTile {
    private final String gid;
    private final List<RuleEntry> neighborRules;
    private final Set<String> attentionList;
    private final Map<RuleEntry, Integer> rulePriorities = new HashMap<>();

    public static class RuleEntry {
        private final String targetId;//符合规则返回的id
        private final String condition;//邻接规则

        public RuleEntry(String targetId, String condition) {
            this.targetId = targetId;
            this.condition = condition;
        }

        public String getTargetId() { return targetId; }
        public String getCondition() { return condition; }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            RuleEntry ruleEntry = (RuleEntry) o;
            return Objects.equals(targetId, ruleEntry.targetId) &&
                    Objects.equals(condition, ruleEntry.condition);
        }

        @Override
        public int hashCode() {
            return Objects.hash(targetId, condition);
        }
    }

    // 原有的Map构造方法（保持兼容性）
    public RuleTile(String gid, Map<String, String> neighborRules, String attentionListStr) {
        this.gid = gid;
        this.neighborRules = new ArrayList<>();
        this.attentionList = new HashSet<>(Arrays.asList(attentionListStr.split(" ")));

        for (Map.Entry<String, String> entry : neighborRules.entrySet()) {
            RuleEntry ruleEntry = new RuleEntry(entry.getKey(), entry.getValue());
            this.neighborRules.add(ruleEntry);
            calculatePriority(ruleEntry);
        }
    }

    // 新增List构造方法
    public RuleTile(String gid, List<RuleEntry> neighborRules, String attentionListStr) {
        this.gid = gid;
        this.neighborRules = new ArrayList<>(neighborRules);
        this.attentionList = new HashSet<>(Arrays.asList(attentionListStr.split(" ")));

        for (RuleEntry ruleEntry : neighborRules) {
            calculatePriority(ruleEntry);
        }
    }

    private void calculatePriority(RuleEntry ruleEntry) {
        String rule = ruleEntry.getCondition();
        int priority = 0;
        for (int i = 0; i < rule.length(); i++) {
            char c = rule.charAt(i);
            if (c == 'y' || c == 'n') {
                priority++;
            }
        }
        rulePriorities.put(ruleEntry, priority);
    }

    public String getGid() { return gid; }
    public List<RuleEntry> getNeighborRules() { return neighborRules; }
    public Set<String> getAttentionList() { return attentionList; }
    public Map<RuleEntry, Integer> getRulePriorities() { return rulePriorities; }
}
